Component({
  data: {
    selected: 0,
    color: "#7A7E83",
    selectedColor: "#3cc51f",
    lastUpdateTime: 0,
    list: [
      {
        pagePath: "/pages/index-new/index",
        iconPath: "/static/tabbar/xuqiu_a.png",
        selectedIconPath: "/static/tabbar/xuqiu_b.png",
        text: "发需求"
      },
      // {
      //   pagePath: "/pages/lookingBuddy/lookingBuddy",
      //   iconPath: "/static/tabbar/jiedan_a.png",
      //   selectedIconPath: "/static/tabbar/jiedan_b.png",
      //   text: "找搭子"
      // },
      {
        pagePath: "/pages/discover/index",
        iconPath: "/static/tabbar/faxiang_a.png",
        selectedIconPath: "/static/tabbar/faxiang_b.png",
        text: "发现"
      },
      {
        pagePath: "/pages/chat/index",
        iconPath: "/static/tabbar/liao_a.png",
        selectedIconPath: "/static/tabbar/liao_b.png",
        text: "聊天"
      },
      {
        pagePath: "/pages/pageMy/index",
        iconPath: "/static/tabbar/me_a.png",
        selectedIconPath: "/static/tabbar/me_b.png",
        text: "我的"
      }
    ]
  },
  
  attached() {
      // 页面加载时设置选中状态
      console.log('TabBar attached, setting initial tab state');
      // 延迟设置初始状态，确保页面完全加载
      setTimeout(() => {
        this.setSelectedTab();
      }, 50);
    },
  
  pageLifetimes: {
    show() {
      // 页面显示时更新选中状态
      console.log('TabBar show lifecycle triggered');
      this.setSelectedTab();
    }
  },
  
  methods: {
    // 供外部调用的公共方法
    setSelectedTab(route = '') {
      try {
        // 防抖处理：50ms内不重复更新（减少延迟）
        const now = Date.now();
        if (now - this.data.lastUpdateTime < 50) {
          console.log('TabBar update skipped due to debounce');
          return;
        }
        
        let currentRoute = route;
        
        if (!route) {
          const pages = getCurrentPages();
          if (!pages || pages.length === 0) return;
          
          const currentPage = pages[pages.length - 1];
          if (!currentPage || !currentPage.route) return;
          
          currentRoute = `/${currentPage.route}`;
        }
        
        // 清理路径：移除尾部斜杠和查询参数，并标准化路径格式
        currentRoute = currentRoute.replace(/\/$/, '').split('?')[0];
        // 确保路径格式与配置一致
        if (!currentRoute.startsWith('/')) {
          currentRoute = '/' + currentRoute;
        }
        
        console.log('TabBar setSelectedTab called with cleaned route:', currentRoute);
        
        const list = this.data.list;
        let foundIndex = -1;
        
        // 创建标准化的路径映射（确保路径精确匹配）
        const pathMapping = {
          '/pages/index-new/index': 0,
          // '/pages/Receiveorders/Receiveorders': 1,
          '/pages/discover/index': 1,
          '/pages/chat/index': 2,
          '/pages/pageMy/index': 3
        };
        
        // 直接查找标准化路径
        if (pathMapping.hasOwnProperty(currentRoute)) {
          foundIndex = pathMapping[currentRoute];
        } else {
          // 回退到模糊匹配（处理大小写差异）
          for (let i = 0; i < list.length; i++) {
            const tabPath = list[i].pagePath.replace(/\/$/, '');
            if (tabPath.toLowerCase() === currentRoute.toLowerCase()) {
              foundIndex = i;
              break;
            }
          }
        }
        
        if (foundIndex !== -1 && foundIndex !== this.data.selected) {
          console.log('Found matching tab index:', foundIndex, 'Current selected:', this.data.selected);
          // 只在索引变化时更新，避免重复设置
          this.setData({
            selected: foundIndex,
            lastUpdateTime: now
          });
          console.log('Tab state updated to:', foundIndex);
        } else if (foundIndex === -1) {
          console.warn('No matching tab found for route:', currentRoute);
        }
      } catch (error) {
        console.error('TabBar setSelectedTab error:', error);
      }
    },
    
    getCurrentPage() {
      try {
        const pages = getCurrentPages();
        if (pages && pages.length > 0) {
          return pages[pages.length - 1];
        }
        return null;
      } catch (error) {
        console.error('获取当前页面失败:', error);
        return null;
      }
    },
    
    switchTab(e) {
      const data = e.currentTarget.dataset;
      const url = data.path;
      const index = data.index;
      
      if (this.data.selected === index) return;
      
      if (!url) {
        console.error('无效的跳转路径');
        return;
      }
      
      console.log('Switching tab to:', url, 'index:', index);
      
      // 使用微信小程序原生API，让系统处理页面跳转
      // 不再手动设置状态，避免双重触发
      wx.switchTab({
        url,
        success: () => {
          console.log('Tab switch success:', url);
          // 页面切换成功后，通过页面生命周期更新状态
          // 不再手动调用setSelectedTab，避免重复
        },
        fail: (error) => {
          console.error('switchTab失败:', error);
        }
      });
    }
  }
});